package com.qiall.boot.userservice.Impl.role;

import com.qiall.assertutil.Assert;
import com.qiall.boot.userservice.data.entity.RoleInfo;
import com.qiall.boot.userservice.data.mapper.RoleMapper;
import com.qiall.boot.userservice.data.mapper.UserMapper;
import com.qiall.common.exception.BusinessResult;
import com.qiall.common.request.BaseRequest;
import com.qiall.common.request.GetByIdRequest;
import com.qiall.user.ability.entity.RoleInfoDTO;
import com.qiall.user.ability.service.role.RoleService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@DubboService
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    UserMapper userMapper;

    /**
     * 插入角色信息
     *
     * @param roleInfoDTO
     * @return
     */
    @Override
    public BusinessResult<Void> createRole(RoleInfoDTO roleInfoDTO) {
        // 前置校验
        Integer count = roleMapper.countByRoleName(roleInfoDTO.getRoleName());
        Assert.isTrue(count == 0, "角色已经存在");
        roleMapper.insert(RoleTrans.trans(roleInfoDTO));
        return BusinessResult.success(null);
    }

    @Override
    public BusinessResult<Void> modeRole(RoleInfoDTO roleInfoDTO) {
        Integer count = roleMapper.countByRoleName(roleInfoDTO.getRoleName());
        if (count > 0) {
            RoleInfo roleInfo = roleMapper.selectByRoleName(roleInfoDTO.getRoleName());
            Assert.isTrue(roleInfoDTO.getRoleId().equals(roleInfo.getId()), "名称重复无法添加");
        }
        roleMapper.update(RoleTrans.trans(roleInfoDTO));
        return BusinessResult.success(null);
    }

    @Override
    public BusinessResult<List<RoleInfoDTO>> getRoleList(BaseRequest baseRequest) {
        List<RoleInfo> roleInfoList = roleMapper.selectAll();
        List<RoleInfoDTO> roleInfoDTOS = roleInfoList.stream().map(x -> RoleTrans.trans(x)).collect(Collectors.toList());
        return BusinessResult.success(roleInfoDTOS);
    }

    @Override
    public BusinessResult<Void> deleteRole(GetByIdRequest request) {
        //前置校验
        Assert.notNull(request.getId(), "id 为空");
        Integer countByRoleId = userMapper.countByRoleId(request.getId());
        Assert.isTrue(countByRoleId.equals(0), "改角色下有用户无法删除");
        roleMapper.delete(request.getId());
        return BusinessResult.success(null);
    }
}
